package jmine.tec.web.front.forms;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import jmine.tec.utils.register.Receiver;
import jmine.tec.web.front.FrontException;
import jmine.tec.web.front.FrontMessages;

/**
 * @author lundberg
 */
public class FormMetadataRegistry implements Receiver<FormMetadata> {

    private Map<Class<?>, FormMetadata> metadata = new HashMap<Class<?>, FormMetadata>();

    /**
     * Finds a form's metadata from it's class
     * 
     * @param <F> form type
     * @param form form
     * @return metadata
     */
    @SuppressWarnings("unchecked")
    public <F> FormMetadata<F> find(F form) {
        Class<?> formClass = form.getClass();
        if (!this.metadata.containsKey(formClass)) {
            throw new FrontException(FrontMessages.FORM_METADATA_NOT_FOUND.create(formClass.getName()));
        }
        return this.metadata.get(formClass);
    }

    /**
     * {@inheritDoc}
     */
    public void register(Collection<? extends FormMetadata> registers) {
        for (FormMetadata meta : registers) {
            this.metadata.put(meta.getFormClass(), meta);
        }
    }

}
